<template>
    <section class="modlude">
        <el-form :inline="true" ref="formSearch" :model="formSearch" class="form_inline" label-width="90px">
            <!-- <el-form-item label="所属组织" size="small">
                <el-cascader ref="cascader" v-model="option1" :options="dataTree" :props="defaultProps2"
                    @change="handleChange" clearable>
                </el-cascader>
            </el-form-item> -->
            <el-form-item label="所属项目" size="small">
                <el-select v-model="formSearch.projectId" placeholder="请选择项目">
                    <el-option v-for="(item,index) in xqTree" :label="item.name" :value="item.id" :key="index">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="检查项名称" size="small">
                <el-input v-model="formSearch.name" placeholder="请输入检查项名称"></el-input>
            </el-form-item>

            <el-form-item>
                <!-- v-if="$root.btnControl.find(item=>item=='view')" -->
                <el-button size="small"   @click="getlist">查 询</el-button>
            </el-form-item>
            <!-- <el-form-item >
          <el-button size="small" @click="resetForm('formSearch')">重 置</el-button>
        </el-form-item> -->
            <el-form-item>
                <!-- v-if="$root.btnControl.find(item=>item=='add')" -->
                <el-button size="small"  @click="addDialoglist"><i class="el-icon-plus"></i> 新 增</el-button>
            </el-form-item>
            <el-form-item>
                <!-- v-if="$root.btnControl.find(item=>item=='delete')" -->
                <el-button size="small" type="danger"  @click="deleInfor(false)">批量删除</el-button>
            </el-form-item>
            <!-- <el-form-item >
            <el-button size="small" @click="">导 出</el-button>
          </el-form-item> -->
        </el-form>
        <el-table :data="formData" style="width: 100%" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="orgName" label="所属组织架构"></el-table-column>
            <el-table-column prop="projectName" label="所属项目"></el-table-column>
            <el-table-column prop="name" label="检查项名称"></el-table-column>
            <el-table-column label="是否多选">
                <template slot-scope="scope">
                    {{scope.row.choose==1?"是":'否'}}
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width=310>
                <template slot-scope="scope">
                    <!-- v-if="$root.btnControl.find(item=>item=='edit')" delete view-->
                    <el-button type="" size="small"  @click="updatalist(scope.row,2)">修 改</el-button>
                    <el-button type="" size="small"  @click="deleInfor(scope.row.id)">删 除</el-button>
                    <el-button type="" size="small"  @click="updatalist(scope.row,3)">详 情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <paging @changePage=handleCurrentPage :get-total='total'></paging>

        <!-- 添加 -->
        <el-dialog :title="jianchaxiang==1? '新增' :jianchaxiang==2?'修改':'详情'" :visible.sync="addDialog" @close="canceladd" :close-on-click-modal="false">
            <div class="cont_box_right">
                <el-form label-position="right" label-width="110px" :model="formPush" ref='addList'>
                    <el-form-item label="选择所属组织" size="small" :rules="{
                        required: true, message: '此项不能为空', trigger: 'blur'
                    }">
                        <el-cascader ref="cascader1" v-model="option2" :options="dataTree" :props="defaultProps2"
                            @change="zuzhiChange1" clearable>
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="选择项目" size="small" prop="projectId" :rules="{
                        required: true, message: '此项不能为空', trigger: 'blur'
                    }">
                        <el-select v-model="formPush.projectId" placeholder="请选择项目">
                            <el-option v-for="(item,index) in xqTree1" :label="item.name" :value="item.id" :key="index">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="检查项名称" size="small" prop="name" :rules="{
                required: true, message: '检查项名称不能为空', trigger: 'blur'
            }">
                        <el-input v-model="formPush.name"></el-input>
                    </el-form-item>

                    <div v-for="(item,index) in formPush.seeds" :key="index">
                        <el-form-item label="检查项内容" size="small" :prop="'seeds.'+index+'.name'" :rules="{
                            required: true, message: '检查项内容不能为空', trigger: 'blur'
                        }">
                            <el-input type="text" v-model.trim="item.name" placeholder="请逐条输入检查项内容"></el-input>
                            <el-button v-if="formPush.seeds.length>1" @click="deleteItem(item, index)" size="small"
                                icon="el-icon-delete" circle>
                            </el-button>
                        </el-form-item>

                    </div>
                    <div style="margin:20px 40px;">
                        <el-button @click="addseedsname"><i class="el-icon-plus"></i> 增加检查项内容</el-button>
                    </div>

                    <el-form-item label="是否多选" prop="choice">
                        <el-radio v-model="formPush.choice" :label="2">否</el-radio>
                        <el-radio v-model="formPush.choice" :label="1">是</el-radio>
                    </el-form-item>
                    <el-form-item label="备注" size="small">
                        <el-input v-model="formPush.remark"></el-input>
                    </el-form-item>
                    <!-- <div class="zhuyi">
                        <p>注意：对于组织架构、项目的选择：</p>
                        <p>1、只选择组织架构、不选择项目：默认该检查项可应用于该组织架构下的所有项目</p>
                        <p>2、注意：对于组织架构、项目的选择：该检查项仅用于该项目</p>
                    </div> -->
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="medium " @click="canceladd">关 闭</el-button>
                <el-button size="medium " v-if="jianchaxiang == 1 || jianchaxiang == 2" @click="addList('addList')">提 交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import paging from "../paging"
    //   import paging1 from "../paging"
    import { updDeviceExamine,getDeviceExamineList, addDeviceExamine, xqSelectList, orgTree, deleteDeviceExamine } from '../../url/api';
    export default {
        data() {
            return {
                jianchaxiang: 1,
                checkStrictly: false,
                bindRole: {},
                showmenuList: [],
                menuList: [],
                option1: [],
                option2: [],
                xqTree: [],
                xqTree1: [],
                isAddorUpdate: 1,//1添加、2修改
                formSearch: {
                    current: 1,
                    size: 10,
                },
                formData: [],//数据
                formData1: [],//数据
                deleBatch: [],//删除数据
                formUpdate: {},//修改表单
                total1: 0,//数据总数
                total: 0,//数据总数
                pages: 0,//页面总数
                addDialog: false,
                updateDialog: false,
                dialog: false,
                formPush: {
                    seeds: [{
                        name: ''
                    }],
                    type: 1,
                    choice: 1,
                    name:'',
                    remark:'',
                },
                dataTree: [],
                defaultProps: {//树状图key定义
                    children: 'data',
                    label: 'name'
                },
                defaultProps2: {
                    children: 'children',
                    label: 'name',
                    value: 'id',
                    expandTrigger: 'hover', checkStrictly: true
                },
            }
        },
        methods: {
            addDialoglist(){
                this.jianchaxiang =1
                this.addDialog = true
            },

            updatalist(row,index) {

                this.jianchaxiang = index
                //console.log(row);
                
                this.formPush.orgId = row.orgId;
                this.formPush.projectId = row.projectId;
                this.formPush.name = row.name;
                this.formPush.seeds=[]
                this.formPush.choice = row.choice;
                this.formPush.remark = row.remark
                this.formPush.id = row.id
                //console.log(row);
                let arry = row.content.split('_')
                arry.forEach(val=>{
                    let seedsname ={
                    name:''
                }
                    seedsname.name = val
                    this.formPush.seeds.push(seedsname)
                    //console.log(seedsname);
                })
                    
                //console.log(this.formPush.seeds);
                
                let treeDef = this.get_OrganizationId2(
                    this.formPush.orgId,
                    this.dataTree,
                    "cascader"
                );
                this.option2 = treeDef;
                let org_tree1 = {
                    orgId: this.formPush.orgId
                }
                xqSelectList(org_tree1).then((res) => {//项目选择列表
                    ////console.log(res)
                    if (res.data.ok) {
                        this.xqTree1 = res.data.data
                        //   if(this.xqTree.length!=0){
                        //     this.formPush.projectId = this.xqTree[0].id
                        //   }
                    }
                })
                this.addDialog = true
            },

            getlist() {
                ////console.log("this.formSearch", this.formSearch);
                getDeviceExamineList(this.formSearch).then((res) => {//查询检查项列表
                    //console.log("检查项列表", res)
                    if (res.data.ok) {
                        this.formData = res.data.data.records.filter((item) => {
                            return item
                        })
                        ////console.log(this.formData);
                        this.total = res.data.data.total*1
                    } else {
                        this.$message(res.data.msg);
                    }
                })
            },
            getInit() {
                // this.getshiwuTypejieshu()
                this.getlist()
                // this.getworkOrderlist()
                xqSelectList({}).then((res) => {//项目选择列表
                    ////console.log(res)
                    if (res.data.ok) {
                        this.xqTree = res.data.data
                    }
                })
                let org_tree = {
                    name: '',
                    status: 1
                }
                orgTree(org_tree).then((res) => {//获取组织列表
                    ////console.log(res)
                    if (res.data.ok) {
                        this.dataTree = res.data.data
                    }
                })
            },
            handleChange(value) {
                if (value.length != 0) {
                    ////console.log(value)
                    this.formSearch.orgId = this.$refs.cascader.getCheckedNodes()[0].data.id
                } else {
                    this.formSearch.orgId = ''
                }
            },
            zuzhiChange1(value) {//改变组织
                if (value.length != 0) {
                    ////console.log(value)
                    this.formPush.orgId = this.$refs.cascader1.getCheckedNodes()[0].data.id
                } else {
                    this.formPush.orgId = ''
                }
                let org_tree1 = {
                    orgId: this.formPush.orgId
                }
                xqSelectList(org_tree1).then((res) => {//项目选择列表
                    console.log(res)
                    if (res.data.ok) {
                        this.xqTree1 = res.data.data
                        //   if(this.xqTree.length!=0){
                        //     this.formPush.projectId = this.xqTree[0].id
                        //   }
                    }
                })
            },

            //新增检查项
            addList(addList) {//添加
                if (!this.formPush.orgId) {
                    this.$message("组织不能为空！")
                    return
                }
                if (!this.formPush.projectId) {
                    this.$message("项目不能为空！")
                    return
                }
                ////console.log("this.formPush", this.formPush)
                ////console.log(this.formPush.seeds);
                let arry = []
                this.formPush.seeds.forEach(item => {
                    arry.push(item.name)
                })
                let content = arry.join('_')

                let params = {
                    choice: this.formPush.choice,
                    content: content,
                    name: this.formPush.name,
                    remark: this.formPush.remark,
                    projectId: this.formPush.projectId,
                    orgId: this.formPush.orgId
                }

                ////console.log(params);

                this.$refs.addList.validate((valid) => {
                    ////console.log("valid", valid)
                    if (valid) {
                        this.$confirm("确定要执行此操作吗？", '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            if(this.jianchaxiang == 1){
                                addDeviceExamine(params).then((res) => {
                                ////console.log("新增", res)
                                if (res.data.ok) {
                                    this.$message({
                                        message: '添加成功',
                                        type: 'success'
                                    });
                                    this.getlist()
                                } else {
                                    this.$message('添加失败')
                                }
                                this.addDialog = false
                            })
                            }else if(this.jianchaxiang == 2){
                                //console.log(params);
                               params.id = this.formPush.id
                                updDeviceExamine(params).then((res) => {
                                ////console.log("新增", res)
                                if (res.data.ok) {
                                    this.$message({
                                        message: '修改成功',
                                        type: 'success'
                                    });
                                    this.getlist()
                                } else {
                                    this.$message('修改失败')
                                }
                                this.addDialog = false
                            })
                            // //console.log(this.formPush);
                            // this.$message('还没有修改接口！')
                            // this.adddialog = false
                            }
                            
                            

                        })

                    } else {
                        ////console.log('error submit!!');
                        return false;
                    }
                });
            },
            //取消新增
            canceladd() {
                this.addDialog = false;
                this.formPush = {
                    seeds: [{
                        name: ''
                    }],
                    type: 1,
                    choose: 0,
                    name:'',
                    remark:'',
                };
                this.option2 = []
                this.jianchaxiang = 1
            },

            deleInfor(ids) {

                let arrId = []
                if (ids) {
                    arrId.push(ids)
                } else {
                    if (this.deleBatch.length != 0) {
                        this.deleBatch.filter((item) => {
                            arrId.push(item.id)
                            return item
                        })
                    }else{
                        this.$message("请勾选要删除的数据！")
                        return
                    }
                }
                this.$confirm("确定要删除吗？", '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteDeviceExamine(arrId).then((res) => {
                        ////console.log("删除", res)
                        if (res.data.ok) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getlist()
                        } else {
                            this.$message('删除失败')
                        }
                    })

                })
            },

            resetForm() {
                this.formSearch = {
                    current: 1,
                    size: 10
                };
                this.option1 = [];
            },

            addseedsname() {
                //console.log(this.formPush.seeds);
                this.formPush.seeds.push({
                    name: '',
                });
                //console.log(this.formPush.seeds);
            },
            deleteItem(item, index) {
                this.formPush.seeds.splice(index, 1);
                // //console.log(this.formfzsh,'删除')
            },

            handleCurrentPage(val) {//页码改变
                this.formSearch.current = val
                this.getlist()
            },
            handleSelectionChange(val, self) {//多选
                this.deleBatch = val
                //console.log(this.deleBatch)
            },

            get_OrganizationId2(ids, treeData, refsName) {
                var _this = this;
                /* 
                  ids 后端返回单选或者多选 的id数组(单选：string,多选为：array)
                  treeData 整个树状数据
                  refsName 级联组件ref值
                 */
                ////console.log(refsName);
                let checkdeType = false; //取 多选true 单选false
                let ValueName = "id"; //取 value 字段
                let childrenName = "children"; //取 children 字段
                let newModel = []; //赋值默认选中数组
                let itemIds = []; //单条id 回显数组
                let returnActive = false; //是否找着对应部门（数据返回单个）
                let lastRow = lastVerify(treeData); //获取最后遍历的id
                if (!checkdeType && !(ids instanceof Array)) ids = [ids]; // 单选 ids 格式转换
                for (let i = 0; i < ids.length; i++) {
                    itemIds = [];
                    returnActive = false;
                    filterChild(ids[i], [], treeData);
                    if (itemIds.length > 0) {
                        if (checkdeType) {
                            //多选
                            newModel.push(itemIds);
                        } else {
                            //单选
                            newModel = itemIds;
                        }
                    }
                }
                /* 数据过滤解释 回显数据绑定 */
                // this.$nextTick(() => {
                //     this.dataForm.defDeptIds = newModel;
                // });
                return newModel;
                /* 过滤子级 */
                function filterChild(id, parentIds, selfArr) {
                    for (let j = 0; j < selfArr.length; j++) {
                        if (returnActive) return false;
                        returnActive = selfArr[j][ValueName] == id;
                        if (returnActive) {
                            parentIds.push(selfArr[j][ValueName]);
                            itemIds = parentIds;
                            return false;
                        } else if (
                            selfArr[j][childrenName] &&
                            selfArr[j][childrenName].length > 0
                        ) {
                            parentIds.push(selfArr[j][ValueName]);
                            filterChild(id, parentIds, selfArr[j][childrenName]);
                        } else {
                            /* 最后一级的最后一个判断 */
                            if (lastRow && selfArr[j][ValueName] == lastRow) {
                                ////console.log("未找到对应部门!", id);
                                parentIds = [];
                                itemIds = parentIds;
                                return false;
                            }
                        }
                        /* 循环结束 未找着父级 */
                        if (j == selfArr.length - 1 && !returnActive) {
                            parentIds.splice(parentIds.length - 1, 1);
                        }
                    }
                }

                /* 是否最子级判断 */
                function lastVerify(allTreeData = treeData) {
                    if (allTreeData && allTreeData.length > 0) {
                        if (
                            allTreeData[allTreeData.length - 1][childrenName] &&
                            allTreeData[allTreeData.length - 1][childrenName].length > 0
                        ) {
                            return lastVerify(allTreeData[allTreeData.length - 1][childrenName]);
                        } else {
                            return lastVerify(allTreeData[allTreeData.length - 1]);
                        }
                    } else {
                        if (allTreeData[ValueName]) return allTreeData[ValueName];
                        return false;
                    }
                }
            },
        },
        mounted() {
            this.getInit()
        },
        components: {
            paging,
            //   paging1
        }
    }
</script>
<style scoped>
    .zhuyi {
        color: #eee;
        font-size: 12px;
        margin: 30px 20px;
    }
    .cont_box_right>>> .el-input{
        display: inline-block;
        max-width: 200px;
    }
</style>